<template>
  <div>
      <div class="table-title" >同区域不同设备报警</div>
      <div class="camera-alarm-table">
        <div class="filter-bar">
          <a-button
            type="primary"
            size="small"
            @click="refreshData"
            style="margin-left: 95%;color: #fff;"
          >
            <template #icon>
              <ReloadOutlined />
            </template>
            刷新
          </a-button>
        </div>
        <a-table
          :columns="columns"
          :data-source="flattenedAlarmList"
          bordered
          :scroll="{y: 245 }"
          row-key="id"
          :rowClassName="getRowClassName"
          :pagination="false"
        >
          <template #equipmentName="{ record }">
            <a 
              @click="handleEquipmentNameClick(record)" 
              style="color:#fff;cursor: pointer; "
            >
              {{ record.device_name }}
            </a>
          </template>
        </a-table>
      </div>
   </div>
</template>

<script lang="ts">
import { defineComponent, ref, computed, onMounted, watch } from 'vue';
import { Table, Button } from 'ant-design-vue';
import { ReloadOutlined } from '@ant-design/icons-vue';
import { useRouter } from 'vue-router';
import { SameAreaDiffDeviceAlarmDetails } from '/@/api/jgBigscreen/jgBigscreen';

export default defineComponent({
  name: 'SameAreaTable',
  props: {
    selectedItem: {
      type: String,
      default: '全部'
    },
    startDate: {
      type: String,
      default: ''
    },
    endDate: {
      type: String,
      default: ''
    }
  },
  setup(props, { attrs, slots, emit, expose }) {
    const router = useRouter();

    // 状态管理
    const timeFilter = ref('default');
    const dateRange = ref([]);
    const rawAlarmData = ref({}); // 存储原始的分组数据
    const alarmList = ref([]);    // 存储展平后的数据

    // 点击设备名称事件处理
    const handleEquipmentNameClick = (record) => {
      console.log('点击设备名称，tid:', record.tid);
      router.push({ 
        name: 'ViewsDeviceManagementInDeviceManagementList', 
        query: { tid: record.tid } 
      });
    }

    // 表格列配置
    const columns = computed(() => [
      {
        title: '企业名称',
        dataIndex: 'enterprise_name',
        key: 'enterprise_name',
        width: 120,
        customCell: (record, index, column) => {
          // 上一行该列数据是否一样（index!==0 从第二行开始，与上一行进行比较）
          if (index !== 0 && record.enterprise_name === alarmList.value[index - 1]['enterprise_name']) {
            return {
              rowSpan: 0, // 表示不渲染
            };
          }
          // 判断下一行是否相等
          let rowSpan = 1;
          for (let i = index + 1; i < alarmList.value.length; i++) {
            if (record.enterprise_name !== alarmList.value[i]['enterprise_name']) {
              break;
            }
            rowSpan++;
          }
          return {
            rowSpan: rowSpan,
          };
        },
      },
      {
        title: '区域名称',
        dataIndex:'region_name',
        key:'region_name',
        width: 100,
        customCell: (record, index, column) => {
          // 上一行该列数据是否一样（index!==0 从第二行开始，与上一行进行比较）
          if (index !== 0 && record.region_name === alarmList.value[index - 1]['region_name']) {
            return {
              rowSpan: 0, // 表示不渲染
            };
          }
          // 判断下一行是否相等
          let rowSpan = 1;
          for (let i = index + 1; i < alarmList.value.length; i++) {
            if (record.region_name !== alarmList.value[i]['region_name']) {
              break;
            }
            rowSpan++;
          }
          return {
            rowSpan: rowSpan,
          };
        },
      },
      {
        title: '设备名称',
        dataIndex: 'device_name',
        key: 'device_name',
        width: 140
      },
      {
        title: '报警时间',
        dataIndex: 'alarm_time',
        key: 'alarm_time',
        width: 140
      },
      {
        title: '设备类型',
        dataIndex: 'device_type',
        key: 'device_name',
        width: 120
      },
    ]);

    // 获取行样式
    const getRowClassName = (record, index) => {
      return index % 2 === 0? 'row-even' : 'row-odd';
    };

    // 刷新数据
    const refreshData = () => {
      console.log('刷新数据:', timeFilter.value, dateRange.value);
      fetchData();
    };

    // 获取数据
    const fetchData = async () => {
      try {
        const response = await SameAreaDiffDeviceAlarmDetails({
           startDate: props.startDate,
           endDate: props.endDate,
           enterpriseId: props.selectedItem.enterprise_id,
        });
        
        // 存储原始数据
        rawAlarmData.value = response;
        
        // 展平数据
        const flattenedList = [];
        if (typeof response === 'object' && response!== null) {
          for (const groupId in response) {
            if (Array.isArray(response[groupId])) {
              flattenedList.push(...response[groupId]);
            }
          }
        }
        
        // 更新展平后的数据
        alarmList.value = flattenedList;
        console.log('展平后的数据:', flattenedList);
      } catch (error) {
        console.error('获取数据失败:', error);
      }
    };

    // 初始化加载数据
    onMounted(() => {
      fetchData();
    });

    watch(() => props.selectedItem, (newValue, oldValue) => {
      if (newValue!== oldValue) {
        console.log('selectedItem 发生变化，重新请求数据');
        fetchData();
      }
    });

    watch(() => props.startDate, (newValue, oldValue) => {
      if (newValue!== oldValue) {
        console.log('startDate 发生变化，重新请求数据');
        fetchData();
      }
    });

    watch(() => props.endDate, (newValue, oldValue) => {
      if (newValue!== oldValue) {
        console.log('endDate 发生变化，重新请求数据');
        fetchData();
      }
    });

    // 计算属性，确保数据格式正确
    const flattenedAlarmList = computed(() => {
      if (Array.isArray(alarmList.value)) {
        return alarmList.value;
      }
      return [];
    });

    return {
      columns,
      flattenedAlarmList,
      handleEquipmentNameClick,
      getRowClassName,
      refreshData,
      fetchData
    };
  }
});
</script>

<style scoped>
::v-deep(.table-title){
  margin-bottom: -7px;
  font-size: 25px;
  font-weight: bold;
  width: 28%;
  color: #CAFFFE;
  position: relative;
  padding: 0;
  padding-left: 3%;
  background-image:url('/@/views/Echarts/jgBigscreen/assets/img/弹窗表头背景.png');
  background-repeat:no-repeat;
  background-size:100% 100%;
  z-index: 20;
}
::v-deep(.ant-table-wrapper .ant-table-pagination-right){
  display: none;
}
.camera-alarm-table {
  background: #fff;
  border-radius: 4px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.09);
  background-image:url('/@/views/Echarts/jgBigscreen/assets/img/弹窗表格背景图.png');
  background-repeat:no-repeat;
  background-size:100% 100%;

  ::v-deep(.ant-table-container){
    background-color:rgb(0,37,39);
    color: #fff;
    ::v-deep(.ant-table-thead .ant-table-cell){
      background: linear-gradient(to bottom, rgb(0, 37, 39), rgb(0, 81, 81));
      color: #fff
    }
    /* 移除行悬停效果 */
    ::v-deep(.ant-table-tbody > tr > td) {
      background-color: transparent !important;
    }
  }
  ::v-deep(.ant-btn-primary){
    background-color: #005155;
  }
}

.filter-bar {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  width: 100%;
}

.text-danger {
  color: #ff4d4f;
}

.text-success {
  color: #52c41a;
}

/* 设备名称链接样式 */
::v-deep(.ant-table-cell a) {
  color: #1890ff;
  text-decoration: none;
}

::v-deep(.ant-table-cell a:hover) {
  color: #40a9ff;
  text-decoration: underline;
}

</style>